package com.qingcloud.common.auth.service.impl;

import com.qingcloud.base.api.remote.admin.AdminApi;
import com.qingcloud.base.remote.pojo.LoginUserDTO;
import com.qingcloud.common.auth.service.MyUserDetailsService;
import com.qingcloud.base.constant.SecurityConstants;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
import javax.annotation.Resource;

//本实现类为通过管理平台用户登录认证，如果为新业务平台或其他平台不同的用户体系，直接增加实现类即可，按定义不同的Account-type即可
@Slf4j
@Service
public class UserDetailServiceImpl implements MyUserDetailsService {

    private static final String ACCOUNT_TYPE = SecurityConstants.DEF_ACCOUNT_TYPE;

    @Resource
    private AdminApi adminApi;

    @Override
    public boolean supports(String accountType) {
        return ACCOUNT_TYPE.equals(accountType);
    }

    @Override
    public UserDetails loadUserByUsername(String username) {
        LoginUserDTO loginUserDTO = adminApi.findUserByName(username);
        if (loginUserDTO == null) {
            throw new InternalAuthenticationServiceException("用户名或密码错误");
        }
        return loginUserDTO;
    }

    @Override
    public UserDetails loadUserByOpenId(String openId) {
        LoginUserDTO loginUserDTO = adminApi.findUserByUserId(openId);
        if (loginUserDTO == null) {
            throw new InternalAuthenticationServiceException("自动登录ID错误");
        }
        return loginUserDTO;
    }

    @Override
    public UserDetails loadUserByMobile(String mobile) {
        LoginUserDTO loginUserDTO = adminApi.findUserByName(mobile);
        if (loginUserDTO == null) {
            throw new InternalAuthenticationServiceException("手机号或密码错误");
        }
        return loginUserDTO;
    }
}
